import loginApi from '@/api/user/loginApi'
import { getAppNav } from '@/App'
import LocalStorageKey from '@/constant/LocalStorageKey'
import ILoginForm from '@/model/form/user/ILoginForm'
import IMenuVO from '@/model/vo/menu/IMenuVO'
import { useAppDispatch, useAppSelector } from '@/store'
import { setLoadMenuFlag } from '@/store/common/commonSlice'
import { setUserBaseInfo, setUserMenuList } from '@/store/user/userSlice'
import { ToastError, ToastSuccess } from '@/util/CommonUtil'
import { maxTryNum, timeoutMsg } from '@/util/http/interceptor'
import { closeSocket } from '@/util/Socket'
import { passwordRSAEncrypt } from '@/util/UserUtil'
import { TabPane, Tabs } from '@douyinfe/semi-ui'
import { Dispatch, SetStateAction, useEffect, useState } from 'react'
import { Navigate } from 'react-router-dom'
import LoginRegisterBase from '../components/LoginRegisterBase/LoginRegisterBase'
import PasswordLogin from '../components/PasswordLogin/PasswordLogin'
import PhoneLogin from '../components/PhoneLogin/PhoneLogin'

export default function Login() {
  const [loading, setLoading] = useState(false)
  const rsaPublicKey = useAppSelector((state) => state.common.rsaPublicKey)
  const appDispatch = useAppDispatch()
  const jwt = localStorage.getItem(LocalStorageKey.JWT)

  useEffect(() => {
    if (!jwt) {
      // 清除登录信息
      localStorage.clear()
      sessionStorage.clear()
      appDispatch(setUserBaseInfo({}))
      // 重置：用户菜单
      appDispatch(setUserMenuList([] as IMenuVO[]))
      // 设置：是否加载过菜单为 false
      appDispatch(setLoadMenuFlag(false))
      // 关闭 socket
      closeSocket()
    }
  }, [])

  if (jwt) {
    return <Navigate to="/admin" />
  }

  return (
    <LoginRegisterBase name="登录">
      <Tabs>
        <TabPane tab="密码登录" itemKey="1" disabled={loading}>
          <PasswordLogin
            submitClick={(form: ILoginForm) => {
              submitClick(form, setLoading, rsaPublicKey)
            }}
            loading={loading}
          />
        </TabPane>
        <TabPane tab="手机快捷登录" itemKey="2" disabled={loading}>
          <PhoneLogin loading={loading} setLoading={setLoading}></PhoneLogin>
        </TabPane>
      </Tabs>
    </LoginRegisterBase>
  )
}

// 点击提交按钮
function submitClick(
  form: ILoginForm,
  setLoading: Dispatch<SetStateAction<boolean>>,
  rsaPublicKey: string
) {
  setLoading(true) // 设置 loading状态
  const passwordTemp = form.password // 密码原始值

  form.password = passwordRSAEncrypt(passwordTemp, rsaPublicKey)

  if (form.hiddenFlag) {
    // socket 连接状态：1 在线 2 隐身
    localStorage.setItem(LocalStorageKey.SOCKET_TYPE, '2')
  } else {
    localStorage.setItem(LocalStorageKey.SOCKET_TYPE, '1')
  }

  doLoginApi(form, maxTryNum, setLoading, passwordTemp, rsaPublicKey)
}

// 调用登录接口
function doLoginApi(
  form: ILoginForm,
  maxTryNum: number,
  setLoading: Dispatch<SetStateAction<boolean>>,
  passwordTemp: string | undefined,
  rsaPublicKey: string
) {
  if (maxTryNum < 0) {
    ToastError(timeoutMsg, 5)
    setLoading(false) // 取消 loading状态
    return
  }
  loginApi(form)
    .then((res) => {
      ToastSuccess('欢迎回来 (oﾟ▽ﾟ)o', 5)
      // 存储令牌
      localStorage.setItem(LocalStorageKey.JWT, res.data.data)
      // 跳转到首页
      getAppNav()('/')
    })
    .catch((e) => {
      if (e.message.includes('timeout')) {
        form.password = passwordRSAEncrypt(passwordTemp, rsaPublicKey)
        doLoginApi(form, maxTryNum - 1, setLoading, passwordTemp, rsaPublicKey)
      } else {
        ToastError(e.message, 5)
        setLoading(false) // 取消 loading状态
      }
    })
}
